package com.lqjava.flowable.serverapp.sys.config.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lqjava.flowable.serverapp.app.cache.Cacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lqjava.flowable.beans.utils.RequestingThread;
import com.lqjava.flowable.beans.utils.RequestingThread.RequestUser;

/**
 * http登录拦截器
 * 验证sign是否存在
 * @author lq 2021年3月21日 19:15:22
 */
@Component
public class ApiLoginInterceptor implements HandlerInterceptor{

	@Autowired
	private Cacher cacher;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		RequestUser user = null;

		String sign = request.getParameter("sign");
		Long timestamp = request.getParameter("timestamp") != null ? Long.valueOf(request.getParameter("timestamp")):0l;
		//可以修改为 2分钟内的请求timestamp验证
		if(sign != null && timestamp > 0) {
			user = cacher.LOGIN.get(sign);
			if(user != null) {
				RequestingThread.REQUEST_USER.set(user);
			}else {
				//sk错误
				response.setStatus(408);
			}
		}else {
			//sk不存在
			response.setStatus(408);
		}
		return user != null;
	}
	

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		RequestingThread.REQUEST_USER.remove();
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
}
